package logic

import (
	"context"
	"fmt"
	"zhihu/models/cache"
	"zhihu/models/mysql"
	"zhihu/pkg"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *zhihurpc.RegisterRequest) (*zhihurpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.RedisDB.Get(l.ctx, "sendSms"+in.Mobile)
	if get.Val() != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}
	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("当前用户已存在，请前往登录")
	}
	user = mysql.User{

		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Mobile),
	}
	err := mysql.DB.Debug().Create(&user).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}
	return &zhihurpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
